package com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.service.business.msg.convert;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.yonyou.iuap.ipaas.connector.sdk.exception.BusinessModuleException;
import com.yonyou.iuap.ipaas.connector.sdk.exception.CommonErrorTypeDefinition;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.api.model.business.msg.BaseToDo;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.api.model.business.msg.extend.*;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.SdwcoatencentConnection;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.service.core.ParamConvertService;
import com.yonyou.iuap.ipaas.connector.sdwcoatencent.internal.utils.LogUtils;
import com.yonyou.yonlinker.ysb.metadata.internal.utils.StringUtils;
import org.apache.commons.lang3.SerializationUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

public class ToDoParamConvertService implements ParamConvertService<BaseToDo, BipTodo> {
    @Override
    public List<BaseToDo> convertForBatchSave(List<BipTodo> list, SdwcoatencentConnection connection) {
        String corpid = connection.getCorpid();
        Long agentid = connection.getAgentid();
        List<BaseToDo> baseTodos = new ArrayList<>();
        String authInterface = connection.getAuthInterface();
        Iterator var7 = list.iterator();
        while(var7.hasNext()) {
            BipTodo todo = (BipTodo)var7.next();
            StringBuilder authUrlBuilder = new StringBuilder();
            authUrlBuilder.append(authInterface);
            List<String> executorIdsList = todo.getExecutorIdsList();
            if (executorIdsList.isEmpty())
                continue;
            Boolean syncFlag = todo.getSyncFlag();
            if (!syncFlag.booleanValue())
                continue;
//            String sourceUnique = todo.getSourceUnique() + "_" + (String)todo.getYyUserIds().get(0);
//            todo.setSourceUnique(sourceUnique);
            String executorIds = executorIdsList.stream().collect(Collectors.joining("|"));
            todo.setTouser(executorIds);
            todo.setAgentid(agentid);
            String webUrl = (todo.getWebUrl() == null) ? "" : todo.getWebUrl();
            String mUrl = (todo.getMUrl() == null) ? "" : todo.getMUrl();
            authUrlBuilder.append("/"+todo.getTenantId()+"/"+executorIds).append("?webUrl="+webUrl).append("&mUrl="+mUrl);
            try {
//                System.out.println(authUrlBuilder.toString());
                //地址处理
//                String state = URLEncoder.encode("bizUrl=" + URLEncoder.encode("webUrl=" + URLEncoder.encode(webUrl, "UTF-8") + "&mUrl=" + URLEncoder.encode(mUrl, "UTF-8"), "UTF-8"), "UTF-8");
//                StringBuilder urlBuilder = new StringBuilder();
//                urlBuilder.append(connection.getAuthHost()).append("/connect/oauth2/authorize").append("?appid=").append(corpid).append("&redirect_uri=").append(URLEncoder.encode(authUrlBuilder.toString(), "UTF-8")).append("&response_type=code&scope=snsapi_base&state=").append(state).append("&agentid=").append(agentid).append("#wechat_redirect");
//                System.out.println(urlBuilder.toString());

                CardAction cardAction=new CardAction();
                MainTitle mainTitle=new MainTitle();
                TemplateCard templateCard=new TemplateCard();
                cardAction.setUrl(authUrlBuilder.toString());
                mainTitle.setTitle(todo.getMsgTitle());
                mainTitle.setDesc(todo.getMsgContent());
                templateCard.setCard_action(cardAction);
                templateCard.setMain_title(mainTitle);
                templateCard.setTask_id(todo.getSourceUnique());
                List<JSONObject> buttonList = new ArrayList<>();
                JSONObject button = new JSONObject();
                button.put("text","待办");
                button.put("style", 1);
                button.put("key", "button_key_" + todo.getSourceUnique());
                button.put("type",1);
                button.put("url",authUrlBuilder.toString());
                buttonList.add(button);
                templateCard.setButton_list(buttonList);
                todo.setTemplate_card(templateCard);
                todo.setMsgtype("template_card");
                baseTodos.add(todo);
            } catch (Exception e) {
                LogUtils.printStacktrace(e);
                throw BusinessModuleException.simpleException("999", "build todo error,errorMsg:" + e.getMessage(), CommonErrorTypeDefinition.CONNECTIVITY);
            }
        }
        return baseTodos;
    }

    @Override
    public List<BaseToDo> convertForBatchDelete(List<BipTodo> list, SdwcoatencentConnection connection) {
        List<BaseToDo> baseTodos = new ArrayList();
        Iterator var4 = list.iterator();

        while(var4.hasNext()) {
            BipTodo todo = (BipTodo)var4.next();
            Boolean syncFlag = todo.getSyncFlag();
            if (syncFlag) {
                baseTodos.add(todo);
                String agentMsgId = todo.getAgentMsgId();
                String msgid =todo.getMsgid();
                if (StrUtil.isNotBlank(agentMsgId)) {
                    BipTodo agentTodo = (BipTodo) SerializationUtils.clone(todo);
                    UpdateTemplateCard updateTemplateCard=new UpdateTemplateCard();
                    updateTemplateCard.setResponse_code(msgid);
                    updateTemplateCard.setUserids(Arrays.asList(agentMsgId));
                    updateTemplateCard.setAgentid(connection.getAgentid());
                    Button button=new Button();
                    updateTemplateCard.setButton(button);
                    agentTodo.setUpdateTemplateCard(updateTemplateCard);
                    baseTodos.add(agentTodo);
                }
            }
        }

        return baseTodos;
    }

    @Override
    public BaseToDo convertForSave(BipTodo objet, SdwcoatencentConnection connection) {
        return null;
    }

    @Override
    public BaseToDo convertForDelete(BipTodo objet, SdwcoatencentConnection connection) {
        return null;
    }
}
